using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace ExamServer.Service
{
  public class RepositoryBase<T, Tid> : IRepositoryBase<T>, IRepositoryBase2<T, Tid> where T : class
  {
    public DbContext dbContext{get;set;}
    public RepositoryBase(DbContext dbcontext)
    {
        this.dbContext=dbcontext;
    }

    #region 查询操作
    public  Task<IEnumerable<T>> GetAllAsync()
    {
      return Task.FromResult(dbContext.Set<T>().AsEnumerable());
    }

    public Task<IEnumerable<T>> GetByConditionAsync(Expression<Func<T, bool>> expression)
    {
      return Task.FromResult(dbContext.Set<T>().Where(expression).AsEnumerable());
    }

    public async Task<T> GetByIdAsync(Tid id)
    {
      return await dbContext.Set<T>().FindAsync(id);
    }

    public async Task<bool> IsExistAsync(Tid id)
    {
        return await dbContext.Set<T>().FindAsync(id)!=null;
    }
    #endregion

    #region 新增操作
    public void Creatre(T entity)
    {
        dbContext.Set<T>().Add(entity);
    }
    #endregion

    #region 修改操作
    public void Update(T entity)
    {
        dbContext.Set<T>().Update(entity);
    }
    #endregion

    #region 删除操作
    public void Delete(T entity)
    {
        dbContext.Set<T>().Remove(entity);
    }
    #endregion
    
    #region 保存操作
    public async Task<bool> SaveAsync()
    {
      return await dbContext.SaveChangesAsync()>0;
    }
    #endregion
  }
}
